//
//  ContactController.m
//  OCDemo
//
//  Created by BH on 15/10/22.
//  Copyright © 2015年 baohan. All rights reserved.
//

#import "ContactController.h"
#import <Masonry/Masonry.h>
#import "PPTranslator.h"
#import "GlobalDefine.h"

@interface ContactController ()<UITableViewDataSource,UITableViewDelegate>
{
    NSArray *dataArr;
    NSMutableArray *pinyinArr;
    NSArray *headerArr;
    NSDictionary *dataDic;

    UITextField *textF;
}

@property(nonatomic,strong)UITableView *table;

@end

@implementation ContactController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self addView];
    [self getData];
    [self addAlphaBetButton];
}

-(void)addView
{
    textF = [[UITextField alloc] init];
    textF.placeholder = @"搜索";
    textF.backgroundColor = [UIColor lightGrayColor];
    [textF addTarget:self action:@selector(textChange:) forControlEvents:UIControlEventEditingChanged];
    textF.clearButtonMode = UITextFieldViewModeWhileEditing;
    [self.view addSubview:textF];
    
    _table = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    _table.dataSource = self;
    _table.delegate = self;
    [self.view addSubview:_table];
    
    [textF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(15);
        make.right.equalTo(self.view).offset(-15);
        make.top.equalTo(self.view).offset(5+64);
        make.height.equalTo(@40);
    }];
    
    [_table mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(textF.mas_bottom).offset(5);
        make.left.right.bottom.equalTo(self.view);
    }];
}

-(void)textChange:(UITextField *)sender
{
    if (![sender.text isEqualToString:@""]) {
        if (([sender.text characterAtIndex:0] > 64 && [sender.text characterAtIndex:0] < 91) || ([sender.text characterAtIndex:0] > 96 && [sender.text characterAtIndex:0] < 123)) {
            //字母转换为大写
            NSString *str = [[sender.text substringToIndex:1] uppercaseString];
            [self searchDataWithAlphabet:str flag:1];
        }else{
        
            [self searchDataWithAlphabet:[sender.text substringToIndex:1] flag:2];
        }
    }else{
    
        [self viewDidLoad];
    }
}

-(void)searchDataWithAlphabet:(NSString *)string flag:(NSInteger)flag
{
    BOOL hadAlp = false;
    NSMutableArray *muAry = [NSMutableArray array];
    
    if (flag == 1) {
        NSArray *allKeys = [dataDic allKeys];
        for (int i = 0; i<allKeys.count; i++) {
            if ([allKeys[i] isEqualToString:string]) {
                NSArray *newAry = [dataDic objectForKey:string];
                hadAlp = true;
                [muAry addObject:newAry];
            }
        }
    }else{
    
        for (int i = 0; i<dataArr.count; i++) {
            for (int j = 0; j<[dataArr[i] count]; j++) {
                if ([[dataArr[i][j] substringToIndex:1] isEqualToString:string]) {
                    NSArray *newAry = [NSArray arrayWithObject:dataArr[i][j]];
                    if (!hadAlp) {
                        hadAlp = true;
                        muAry = [NSMutableArray array];
                    }
                    [muAry addObject:newAry];
                }
            }
        }
    }
    
    if (!hadAlp) {
        dataArr = @[@[]];
    }else{
        dataArr = muAry;
    }
    
    UITableView *searchtable = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    searchtable.dataSource = self;
    searchtable.delegate = self;
    [self.view addSubview:searchtable];
    
    [searchtable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(textF.mas_bottom).offset(5);
        make.left.right.bottom.equalTo(self.view);
    }];
}

-(void)getData
{
    NSString *str = @"初彩   玉琬   鑫蕾   栀淑   冰寒   婷雪   格帆   冬美   昭昭   慧珠   婷丽   家桂   沛雅   俊初   花彩   格洁   紫欣   格梦   可香   淑锦  函璐   桂鸿   锦鑫   美枫   初楠   月彩   静芝   玉茜   锦华   诗萱   鸿明   梦香   月蕾   琪锦   帆家   昭弦   桂芸   萱俊   帛林   彩芸  初采   @ww   漫寒   姿嘉   嘉家   莲霞   玥雪   梅薇   嘉凡   婷彦   柔采   初洁   琪呈   静弦   祥璐   璇春   彩橘   怡格   香雪   雪锦  茜娅   初雯   雅灵   彩彦   淑婷   美妍   雅桃   锦雅   彩妍   雅婧   弦锦   昭琬   桐蓓   Caixin   萱帛   雪栀   美华   涵梦   娅梦   岚怡  楠璟   欢雪   可梓   欣雅   雪萱   昕慧   灵芳   馨蔚   舒雪   初玥   敏欣   茹莲   枫雅   鸿雪   梅霞   彩林   桂采   妍初   采梦   文云  蓓栀   彩文   锦彤   静柔   玥林   雪妍   彤珊   桂萱   正莉   薇露   华莉   梦慧   蔚鑫   彩云   露柏   锦美   璟珊   玲柔   雅媛   薇鑫  正文   婧锦   璐柏   瑶璐   雪月   锦桃   2398   玉采   鑫梦   帆琛   昕凡   彩敏   霞萱   梓彩   洁楠   碧初   琬玥   月帛   桂帛   欣曼  洁玲   琬琛   锦涵   静雪   静曼   花锦   梦锦   曦梦   萱彩   雯雪   柏格   帆琪   丽梦   杉锦   婷梅   呈怡   碧桂   杉柔   婷漫   yulei  紫舒   桃蓓   鹤馨   玲帆   美美   玥馨   帆锦   璐锦   碧珊   彦锦   锦月   媛美   彦彩   初漫   云月   彦楠   怡昕   妮慧   琪碧   锦霞  玥文   灵雨   雅花   欣璟   桐楠   娜曦   薇弦   雅芳   芳初   雨曦   美锦   怡美   婧凌   萱格   慧璟   蔚春   诗呈   梅梦   彦雪   敏媛  柔惠   岚香   香珠   雪馨";
    
    NSMutableDictionary *muDic = [NSMutableDictionary dictionary];
    NSMutableString *muStr = [NSMutableString string];
    
    for (int i = 0; i<str.length; i++) {
        NSString *subStr = [str substringWithRange:NSMakeRange(i, 1)];
        
        if ([subStr isEqualToString:@" "]) {
            muStr = [NSMutableString string];
        }else{
        
            [muStr appendString:subStr];
            NSString *muSubStr = nil;
            if ((i+1)<str.length) {
                muSubStr = [str substringWithRange:NSMakeRange(i+1, 1)];
            }
            
            if ([muSubStr isEqualToString:@" "] || (i+1)>str.length) {
                //转成了可变字符串
                NSMutableString *strC = [NSMutableString stringWithString:muStr];
                //先转换为带声调的拼音
                CFStringTransform((CFMutableStringRef)strC, NULL, kCFStringTransformMandarinLatin, NO);
                //再转换为不带声调的拼音
                CFStringTransform((CFMutableStringRef)strC, NULL, kCFStringTransformStripDiacritics, NO);
                //转化为大写拼音
                NSString *pinyin = [strC capitalizedString];
                NSString *capitalStr = [pinyin substringToIndex:1];
                NSArray *allKeys = [muDic allKeys];
                BOOL hasKey = false;
                
                for (int i = 0; i<allKeys.count; i++) {
                    if ([capitalStr isEqualToString:allKeys[i]]) {
                        hasKey = true;
                        [[muDic objectForKey:capitalStr] addObject:muStr];
                        break;
                    }
                }
                if (!hasKey) {
                    NSMutableArray *muArr = [NSMutableArray array];
                    [muArr addObject:muStr];
                    [muDic setObject:muArr forKey:capitalStr];
                }
            }
        }
    }
    
    NSArray *allKeys = [muDic allKeys];
    NSMutableArray *keyAscend = [NSMutableArray array];
    for (int i = 0; i<allKeys.count; i++) {
        BOOL hasInserted = false;
        for (int j=0; j<keyAscend.count; j++) {
            if ([keyAscend[j] compare:allKeys[i]] > 0) {
                hasInserted = true;
                [keyAscend insertObject:allKeys[i] atIndex:j];
                break;
            }
        }
        if (!hasInserted) {
            [keyAscend addObject:allKeys[i]];
        }
    }
    
    headerArr = [NSArray arrayWithArray:keyAscend];
    NSMutableArray *dataMut = [NSMutableArray array];
    for (int i = 0; i<headerArr.count; i++) {
        [dataMut addObject:[muDic objectForKey:headerArr[i]]];
    }
    
    dataArr = [NSArray arrayWithArray:dataMut];
    dataDic = [NSDictionary dictionaryWithObjects:dataArr forKeys:headerArr];
}

//添加索引
-(void)addAlphaBetButton
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(SCREEN_W-30*SCREEN_W/375, 55*SCREEN_H/667*2, 30*SCREEN_W/375, SCREEN_H-55*SCREEN_H/667*2)];
    view.backgroundColor = [UIColor whiteColor];
    view.tag = 100;
    [self.view addSubview:view];
    
    float w = view.bounds.size.width;
    float h = view.bounds.size.height/[headerArr count];
    
    for (int i = 0; i<headerArr.count; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(0, h*i, w, h);
        [button setTitle:headerArr[i] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(alphaBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [view addSubview:button];
    }
}

//滚动到相对索引位置
-(void)alphaBtnClick:(UIButton *)sender
{
    NSIndexPath *scrollindex = [NSIndexPath indexPathForRow:0 inSection:[headerArr indexOfObject:sender.titleLabel.text]];
    [_table scrollToRowAtIndexPath:scrollindex atScrollPosition:UITableViewScrollPositionTop animated:YES];
}

#pragma mark - tableview datasource & delegate
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (tableView == _table) {
        return 10*SCREEN_H/667;
    }else{
        return 0;
    }
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [dataArr[section] count];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return dataArr.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    
    cell.contentView.backgroundColor = [UIColor whiteColor];
    cell.textLabel.textColor = [UIColor orangeColor];
    cell.textLabel.text = dataArr[indexPath.section][indexPath.row];
    cell.textLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:16.f];
    
    return cell;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UILabel *lable = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 20*SCREEN_W/375, 10*SCREEN_H/667)];
    lable.text = headerArr[section];
    lable.textColor = [UIColor blueColor];
    lable.font = [UIFont fontWithName:@"Helvetica-Bold" size:13.f];
    
    return lable;     
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

@end
